package app

import (
	"fmt"
	logger "gitee.com/visons/gopkg/log"
	"github.com/micro/go-micro/config"
	"github.com/micro/go-micro/config/source"
	"github.com/micro/go-micro/config/source/file"
	"gopkg/app/interfaces"
	"gopkg/app/internal/service-manager"
	"gopkg/app/internal/system-manager"
	"gopkg/util/action-queue"
	"io"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"sync"
	"syscall"
)

type app struct {
	configDir      string
	c              config.Config
	svm            interfaces.ServiceManager
	sm             interfaces.SystemManager
	actionQueue    action_queue.ActionQueue
	fileLogHandler io.WriteCloser
}

var instance *app
var instanceOnce sync.Once

func App() *app {
	instanceOnce.Do(func() {
		instance = &app{
			actionQueue: action_queue.NewActionQueue(),
			svm:         service_manager.NewServiceManager(),
			sm:          system_manager.NewSystemManager(),
		}
		instance.actionQueue.EnableCapturePanic(true)
	})
	return instance
}

func (a *app) SetConfigDir(dir string) {
	a.configDir = dir
}

func (a *app) Init() {
	a.initConfig()
	a.initLog()
}

func (a *app) initLog() {
	logConfig := struct {
		LogBase       string
		LogLevel      int
		LogToStdout   bool
		RollSize      int
		FlushInterval int64
		CheckEveryN   int
	}{
		"logs", 5, true, 256 * 1024 * 1024, 10, 100,
	}

	err := a.Config().Get("LogConfig").Scan(&logConfig)
	if err != nil {
		panic(fmt.Sprintf("read logger config  %v", err))
	}
	var logHander io.Writer
	fileLogHandler, err := logger.NewRotatingFileAtDayHandler(logConfig.LogBase, logConfig.RollSize, logConfig.FlushInterval, logConfig.CheckEveryN, false)
	if err != nil {
		panic(fmt.Sprintf("new logger handler %s", err))
	}
	a.fileLogHandler = fileLogHandler
	logHander = fileLogHandler

	if logConfig.LogToStdout {
		logHander = io.MultiWriter(fileLogHandler, os.Stdout)
	}

	logger.SetLevel(logger.Level(logConfig.LogLevel))
	logger.SetOutput(logHander)
	logger.SetFormatter(&logger.JSONFormatter{})
}

func (a *app) initConfig() {
	configSource := []source.Source{}
	err := filepath.Walk(a.configDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		if info.IsDir() {
			if path != a.configDir {
				return filepath.SkipDir
			}
		} else {
			if strings.HasSuffix(info.Name(), ".toml") {
				configSource = append(configSource, file.NewSource(file.WithPath(path)))
			}
		}
		return nil
	})
	if err != nil {
		panic(fmt.Sprintf("load app config source %v", err))
	}
	a.c = config.NewConfig()
	err = a.c.Load(configSource...)
	if err != nil {
		panic(fmt.Sprintf("load app config %v", err))
	}
}

func (a *app) WaitSignal() {
	c := make(chan os.Signal, 1)

	signal.Notify(
		c,
		syscall.SIGQUIT,
		syscall.SIGTERM,
		syscall.SIGINT,
		syscall.SIGSEGV,
	)

	for {
		s := <-c
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, syscall.SIGSEGV:
			a.Stop()
			return
		default:
			return
		}
	}
}
func (a *app) Start() {
	a.actionQueue.StartLoop()
	a.startService()
	a.startSystem()
}

func (a *app) Stop() {
	a.stopSystem()
	a.stopService()
	a.actionQueue.StopLoop()
	a.actionQueue.Wait()
	a.fileLogHandler.Close()
}

func (a *app) startService() {
	a.svm.Awake()
	a.svm.Init()
	a.svm.Run()
}

func (a *app) startSystem() {
	a.sm.Awake()
	a.sm.Init()
	a.sm.Run()
}

func (a *app) stopSystem() {
	a.sm.BeforeShut()
	a.sm.Shut()
}

func (a *app) stopService() {
	a.svm.BeforeShut()
	a.svm.Shut()
}

func (a *app) Config() config.Config {
	return a.c
}

func (a *app) ServiceManager() interfaces.ServiceManager {
	return a.svm
}

func (a *app) SystemManager() interfaces.SystemManager {
	return a.sm
}

func (a *app) PostAction(action func()) {
	a.actionQueue.Post(action)
}
